package com.azkj.album.network.networkframe.net;

import android.app.Activity;
import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.azkj.album.MyApplication;
import com.azkj.album.dto.MessageEvent;
import com.azkj.album.dto.MessageType;
import com.azkj.album.network.ConfigStorage;
import com.azkj.album.network.networkframe.bean.BaseResp;
import com.azkj.album.network.utils.StoreUtils;
import com.azkj.album.network.utils.ToastUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.nio.charset.Charset;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;


public class TokenInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {

        Request request = chain.request()
                .newBuilder()
                .header("token", "" + ConfigStorage.getInstance().getToken())
                .removeHeader("User-Agent")
                .addHeader("User-Agent", getUserAgent())
//                .addHeader("Connection","close")
                .build();
        ;
        Response response = chain.proceed(request);

        //根据和服务端的约定判断token过期
        final String msg = isTokenExpired(response);
        if (!TextUtils.isEmpty(msg)) {
            StoreUtils.clear();
            final Activity current = MyApplication.getCurrentActivity();
            if (current != null) {
                current.runOnUiThread(() -> ToastUtils.showCenterToast("您的账号在另外一台设备登录，请您注意账号安全。"));
            }
            EventBus.getDefault().post(new MessageEvent(MessageType.TYPE_START_LOGIN_ACTIVITY, null));

        }
        return response;

    }


    private String isTokenExpired(Response response) {
        try {
            if (response.isSuccessful()) {
                return null;
            } else if (response.code() == 401) {
                ResponseBody responseBody = response.body();
                BufferedSource source = responseBody.source();
                source.request(Long.MAX_VALUE);
                Buffer buffer = source.buffer();
                Charset charset = Charset.forName("UTF-8");
                MediaType contentType = responseBody.contentType();
                if (contentType != null) {
                    charset = contentType.charset(Charset.forName("UTF-8"));
                }
                String bodyString = buffer.clone().readString(charset);
                BaseResp httpResult = JSON.parseObject(bodyString, BaseResp.class);
                return httpResult.getMsg();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;

    }

    private String getUserAgent() {
        String userAgent;
        userAgent = System.getProperty("http.agent");
        StringBuilder sb = new StringBuilder();
        for (int i = 0, length = userAgent.length(); i < length; i++) {
            char c = userAgent.charAt(i);
            if (c <= '\u001f' || c >= '\u007f') {
                sb.append(String.format("\\u%04x", (int) c));
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }


}
